/* eslint-disable */
import { insertMoment } from '../../lib/utils.js';
import { inputData } from './cwbbData.js';
import { handleStep10, handleStep11, cwbbIsReport, cwbbReportStart } from './cwbbReport.js';
import {handleSmallIndex,handleSmallStep1,handleSmallStep2,handleSmallStep3} from './smallZeroReport.js';
import {incomeReport} from './incomeTaxReport.js';
import {sendSbList} from  './tool.js'
import { zeroReportFail, asyncSetInterval, fixZeroInfo, currentToTaxindex  } from '../../lib/zeroReportUtils.js';

function nextTick(findObj,tick){
  function doIt(){
    var obj=findObj()
    if(!obj){
      setTimeout(()=>{
        nextTick(findObj);
      },200);
    }
  }
  if(tick){
    setTimeout(doIt,tick);
  }else{
    doIt();
  }
}

const pages={
  "index":"/xxmh/html/index_login.html",
  "step1":"/xxmh/html/index_origin.html",
  "step10":"/sbzx-cjpt-web/biz/setting/cwbbydy",
  "step11": "biz/cb/cwbb_qykjzz_ybqy_wzx",
  "step12": "biz/cb/cwbb_xqykjzz",
  "step2":"/sbzs-cjpt-web/biz/sbzs/ybnsrzzs",
  "smallStep2":"/sbzs-cjpt-web/biz/sbzs/xgmzzs",
  "step3":"/sbzs-cjpt-web/biz/sbzs/lhfjssb",
  "incomeStep":"/sbzx-cjpt-web/biz/sb/qysds_a_18yjd"
  
};

const isPage=(name)=>{
  return window.location.href.includes(pages[name])
}

let currentZeroInfo;

const startZeroReport = async (data) => {
  currentZeroInfo=data.data.currentZeroInfo;
  let urls = [
    'https://etax.beijing.chinatax.gov.cn/sso/login?service=https://etax.beijing.chinatax.gov.cn/xxmh/html/index_login.html',
  ];
  if (urls.includes(window.location.href)) {
    handleLogin(data.data.currentZeroInfo);
  } else {
    zeroReportPage(currentZeroInfo);
  }
  
};

const handleIndex=()=>{
  nextTick(()=>{
    var btn=$('#cygn a:eq(0)');
    if(btn.length){
      btn.click();
      return true;
    }
  },1000)

}

const handleLogin=(info)=>{
  var btn=$("[lay-id='zhdl'] .layui-form-radio");
  window.sessionStorage.setItem('isZero',true);
  // window.sessionStorage.setItem('isCwbb',true);
  console.log(info);
  if(info.zzsType==="小规模纳税人"){
    window.sessionStorage.setItem('isSmall',true);
  }
  btn.click();
  nextTick(()=>{
    var userName=$("[name='userNameQy']"),password=$("[name='passWordQy']");
    userName.val(info.nationalTaxNo);
    nextTick(()=>{
      password.val(info.nationalTaxPass);
      return true;
    })
    return true;
  },300);
}

const handleStep1= async (currentZeroInfo)=>{
  nextTick(()=>{
      if($("#ifrMain").length && $("#ifrMain").contents().find('#lhsbIframe').length && $("#ifrMain").contents().find('#lhsbIframe').contents().find("#gdslhsb tr:eq(1) .layui-btn:eq(0)").length){
        let str=$("#ifrMain").contents().find('#lhsbIframe').contents().find("#gdslhsb tr:eq(1) .layui-btn:eq(0)").attr("href");
        str=str.replace('javaScript:','');
        $("#ifrMain").contents().find('#lhsbIframe')[0].contentWindow.eval(str);
        nextTick(()=>{
          if($("#ifrMain").contents().find("#layui-layer2 .layui-btn-xs:eq(1)").length){
            let str=$("#ifrMain").contents().find("#layui-layer2 .layui-btn-xs:eq(1)").attr("onclick");
            str=str.replace('javaScript:','');
            $("#ifrMain")[0].contentWindow.eval(str);
            nextTick(()=>{
              window.close();
              return true;
            },1000)
            return true;
          }
        },1000)
        return true;
      }
  })
}

let closeBtn = async () => {
  return new Promise(resolve => {
    setTimeout(() => {
      let btn = $('.layui-layer-btn0');
      if(btn.length > 0) {
        btn[0].click();
      }
      resolve(true);
    }, 2000);
  })
}

const handleStep2= async ()=>{
  await closeBtn();
  // return true;
  nextTick(()=>{
    if($("#btnSave").length){
      $("#btnSave").click();
      window.setTimeout(()=>{
        nextTick(()=>{
          if($("#btnSave").length){
            $("#btnSave").click();
            nextTick(()=>{
              if($("#frmMain")[0].contentWindow){
                $("#frmMain")[0].contentWindow.eval('Message.doHandler("ok",undefined)');
                //layui-layer-shade3
                nextTick(()=>{
                  if($("#layui-layer-shade3").length){
                    return false;
                  }else{
                    nextTick(()=>{
                      if($("#frmMain").length && $("#frmMain").contents().find('#frmSheet').length){
                        let dom=$("#frmMain").contents().find('#frmSheet').contents().find("[ng-bind='nsrjbxx.frxm']");
                        let txt=$("#frmMain").contents().find('#frmSheet').contents().find("[ng-model='slxxForm.smr']");
                        if(dom.length && txt.length && dom.html()){
                          let name=dom.html();
                          let ngWindows =
                            $("#frmMain").length &&
                            $("#frmMain").contents().find("#frmSheet")[0].contentWindow;
                          let angular = ngWindows.angular;
                          let controllerScope = angular.element("#viewCtrlId").scope();
                          controllerScope.slxxForm.smr = name;
                          angular.element("#viewCtrlId").scope().$apply();
                          ngWindows.parent.formulaEngine.apply($(txt[0]).attr('jpath'), txt.val(), null);
                          // txt.val(name);
                          window.frames[0].prepareMakeYbnsrzzs();
                          nextTick(()=>{
                            let btn=$('.layui-layer-btn0');
                            if(btn.length){
                              btn.click();
                              nextTick(()=>{
                                let btn=$('#layui-layer4 .layui-layer-btn0');
                                if(btn.length){
                                  btn.click();
                                  nextTick(()=>{
                                    let content=$("#frmMain").contents().find('.layui-layer-content');
                                    if($("#frmMain")[0].contentWindow && $("#frmMain")[0].contentWindow.yesHandler){
                                      $("#frmMain")[0].contentWindow.yesHandler();
                                      return true;
                                    }
                                  },10000);
                                }
                              },1000);
                              //$("#frmMain")[0].contentWindow.submitPdf('N');
                              return true
                            }
                          })
                          return true;
                        }
                      }
                    },1000)
                    return true;
                  }
                },2000)
                return true;
              }
            },2000)
            return true;
          }
        })
      },2000)
      return true;
    }
  })
}



const handleStep3=()=>{
  insertMoment();
  nextTick(()=>{
    if($("#frmMain").length && $("#frmMain").contents().find('#frmSheet').length){
      let dom=$("#frmMain").contents().find('#frmSheet').contents().find("[ng-model='fjsnsrxxForm.zjhm']");
      let txt=$("#frmMain").contents().find('#frmSheet')[0].contentWindow.$("[ng-model='fjssbInitData.dlrsfzhXs']");
      if(dom.length && txt.length && dom.val()!=''){
        let name=dom.val();
        txt.focus();
        txt.val(name);
        txt.blur();
        window.setTimeout(()=>{
          window.frames[0].prepareMake(true);
          nextTick(()=>{
            // let btn=$("#frmMain").contents().find('.layui-layer-btn0');
            let btn=$('.layui-layer-btn0');
            if(btn.length){
              // $("#frmMain")[0].contentWindow.$('.layui-layer-btn0').click();
              $('.layui-layer-btn0').click();
              nextTick(()=>{
                let btn=$('.layui-layer-btn0');
                if(btn.length){
                  btn.click();
                  nextTick(()=>{
                    let frmMain = $('#frmMain');
                    if (frmMain.length && frmMain.contents().find('body > div > h3').length) {
                      if (frmMain.contents().find('body > div > h3').text().includes('申报成功')) {
                        // currentToTaxindex({});
                        setTimeout(() => {
                          window.location.href = "/xxmh/html/index_login.html";
                        }, 1000);
                      }
                    }
                    // let result=$("#frmMain").contents().find('h3.font-green');
                    // if(result.length){
                    //   sendSbList(currentZeroInfo);
                    //   setTimeout(()=>{
                    //     window.sessionStorage.clear();
                    //     window.location.href="http://etax.beijing.chinatax.gov.cn/sso/logout?service=http%3A%2F%2Fetax.beijing.chinatax.gov.cn%2Fxxmh";
                    //   },2000);
                    //   return true;
                    // }
                  }, 2000)
                }
              },1000);
              return true
            }
          },500)
        },500);
        return true;
      }
    }
  },5000);

}

const ybnslzzsType = () => {
  let trs = $("#ifrMain").contents().find('div.layui-layer-content > div > table > tbody > tr');
  let ybjc = Array.from(trs).find(item => $(item).text().includes('一表申报'));
  if(ybjc) {
    $(ybjc).find('button')[0].click();
    setTimeout(() => {
      window.postMessage({event: 'closeTabs'});
    }, 1000);
  }
}

let reportList = (currentZeroInfo) => {
  let {recordList} = currentZeroInfo;
  asyncSetInterval(() => {
    if($("#ifrMain").length && $("#ifrMain").contents().find('#lhsbIframe').length) {
      let lhsbIframe =  $("#ifrMain").contents().find('#lhsbIframe').contents();
      let sfsb = lhsbIframe.find('div[id="searchTable"] tr.ng-scope');
      if (sfsb.length) {
        let dbList = Array.from(sfsb).filter(tr => $(tr).find('td').length >= 8).map(item => {
          let startTime = $(item).find('td:nth-child(4)').text().split('-');
          let endTime = $(item).find('td:nth-child(5)').text().split('-');
          let declareName = $(item).find('td:nth-child(2)').text();
          let accountBook = endTime[0] + '-' + endTime[1];
          let month = parseInt(endTime[1]) -parseInt(startTime[1]);
          let isSuccess = $(item).find('td:nth-child(8)').text().includes('已申报') || $(item).find('td:nth-child(8)').text().includes('更正财报');
          return {
            declareName,
            accountBook,
            declareCycle: month === 11 ? 'year' : month === 2 ? 'season' : 'month',
            isSuccess
          }
        });
        if(dbList.length > recordList.length) {
          fixZeroInfo({ recordList: dbList });
          setTimeout(() => {
            window.location.reload();
          }, 1000);
          return true;  
        } else {
          // // 财务报表
          let cwbb = recordList.find(item => item.declareName.includes('财务报表') || item.declareName.includes('企业会计准则'));
          if(cwbb && !cwbb.isSuccess) {
            cwbbReportStart(currentZeroInfo);
            return true;
          }
          // 增值税-一般纳税人
          let zzsYbnsr = recordList.find(item => item.declareName.includes('增值税(适用于一般纳税人)'));
          let zzsYbnsrBtn = Array.from(sfsb).find(tr => $(tr).find('td:nth-child(2)').text().includes('增值税(适用于一般纳税人)'));
          if (zzsYbnsrBtn && $(zzsYbnsrBtn).find('td:nth-child(8)').text().includes('已申报')){
            fixZeroInfo({ recordList: [{...zzsYbnsr, isSuccess: true}] });
          } else if(zzsYbnsr && !zzsYbnsr.isSuccess) {
            $(zzsYbnsrBtn).find('td:nth-child(8) > a')[0].click();
            setTimeout(() => {
              // 选择申报类型
              ybnslzzsType();
            }, 1000);
            return true;
          }
          // 增值税-小规模
          let zzsXgm = recordList.find(item => item.declareName.includes('增值税(适用于小规模纳税人)'));
          let zzsXgmBtn = Array.from(sfsb).find(tr => $(tr).find('td:nth-child(2)').text().includes('增值税(适用于小规模纳税人)'));
          if (zzsXgmBtn && $(zzsXgmBtn).find('td:nth-child(8)').text().includes('已申报')){
            fixZeroInfo({ recordList: [{...zzsXgm, isSuccess: true}] });
          } else if(zzsXgm && !zzsXgm.isSuccess) {
            $(zzsXgmBtn).find('td:nth-child(8) > a')[0].click();
            setTimeout(() => {
              window.postMessage({event: 'closeTabs'});
            }, 1000);
            return true;
          }
          // 附加税
          let dfjyfjs = recordList.find(item => item.declareName.includes('地方教育附加'));
          let dfjyfjsBtn = Array.from(sfsb).find(tr => $(tr).find('td:nth-child(2)').text().includes('地方教育附加'));
          if (dfjyfjsBtn && $(dfjyfjsBtn).find('td:nth-child(8)').text().includes('已申报')){
            fixZeroInfo({ recordList: [{...dfjyfjs, isSuccess: true}] });
          } else if(dfjyfjs && !dfjyfjs.isSuccess) {
            $(dfjyfjsBtn).find('td:nth-child(8) > a')[0].click();
            setTimeout(() => {
              window.postMessage({event: 'closeTabs'});
            }, 1000);
            return true;
          }
          let jyfjs = recordList.find(item => item.declareName.includes('教育费附加'));
          let jyfjsBtn = Array.from(sfsb).find(tr => $(tr).find('td:nth-child(2)').text().includes('教育费附加'));
          if (jyfjsBtn && $(jyfjsBtn).find('td:nth-child(8)').text().includes('已申报')){
            fixZeroInfo({ recordList: [{...jyfjs, isSuccess: true}] });
          } else if(jyfjs && !jyfjs.isSuccess) {
            $(jyfjsBtn).find('td:nth-child(8) > a')[0].click();
            setTimeout(() => {
              window.postMessage({event: 'closeTabs'});
            }, 1000);
            return true;
          }
          let csfjs = recordList.find(item => item.declareName.includes('城市维护建设税'));
          let csfjsBtn = Array.from(sfsb).find(tr => $(tr).find('td:nth-child(2)').text().includes('城市维护建设税'));
          if (csfjsBtn && $(csfjsBtn).find('td:nth-child(8)').text().includes('已申报')){
            fixZeroInfo({ recordList: [{...csfjs, isSuccess: true}] });
          } else if(csfjs && !csfjs.isSuccess) {
            $(csfjsBtn).find('td:nth-child(8) > a')[0].click();
            setTimeout(() => {
              window.postMessage({event: 'closeTabs'});
            }, 1000);
            return true;
          }
          // 企业所得税
          let qysds = recordList.find(item => item.declareName.includes('企业所得税(月季报'));
          if(qysds && !qysds.isSuccess) {
            let qysdsBtn = Array.from(sfsb).find(tr => $(tr).find('td:nth-child(2)').text().includes('企业所得税(月季报'));
            $(qysdsBtn).find('td:nth-child(8) > a')[0].click();
            setTimeout(() => {
              window.postMessage({event: 'closeTabs'});
            }, 1000);
            return true;
          }
          setTimeout(() => {
            window.location.reload();
          }, 20000);
          // 申报完成
          window.postMessage(
            {
              event: 'zeroReportBack',
              data: {...currentZeroInfo}
            },
            '*'
          );
          return true;
        }
      }
    }
  }, 1000)
}

const zeroReportPage = (currentZeroInfo)=>{
  if(isPage('index')){
    handleIndex();
  }
  if(isPage('step1')){
    reportList(currentZeroInfo);
  }
  if(isPage('step2')){
    handleStep2();
  }
  if(isPage('smallStep2')){
    handleSmallStep2(currentZeroInfo);
  }
  if(isPage('step3')){
    handleStep3();
  }
  if(isPage("incomeStep")){
    incomeReport(currentZeroInfo);
  }
  return true;
}


export {
  startZeroReport,
  // checkZeroReport
};
